import { Component, OnInit, Input } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

import { HttpService } from 'src/app/shared/service/http.service';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';

import { EventService } from './../../shared/service/event.service';

@Component({
  selector: 'app-signing-on',
  templateUrl: './signing-on.component.html',
  styleUrls: ['./signing-on.component.scss'],
})
export class SigningOnComponent implements OnInit {
  @Input() tagData: any;
  siginMoney: any; // 签约金
  payMoney: any; // 佣金
  process: any;
  marginLeft:any;
  formGroup: FormGroup = new FormGroup({});
  allLabel: any = {};
  constructor( 
    private eventService: EventService,
    private appGlobalService: AppGlobalService,
    private httpService: HttpService
    ) { }

  ngOnInit() {
    // this.demoData();sigin-pay
    this.payMoney = 0.00;
    this.siginMoney = 0.00;
    this.process = 0.0;
    this.marginLeft = '-2.25rem';
    if (  this.tagData.data.card && this.tagData.data.card.process && this.tagData.data.card.process.currentPrice) {
       const currentPrice = this.tagData.data.card.process.currentPrice.replace(',' , '');
       const end = this.tagData.data.card.process.endValue.replace(',' , '');
       this.process = Number(currentPrice)  / Number(end) * 100 + '%';
       console.log('进度：' + this.process);
       setTimeout(() => {
        const x = document.getElementById("card-value") as HTMLElement ;  // 找到回元素
        this.marginLeft = -(((x.offsetWidth * 0.5) / 16) - 0.25) + 'rem';
        console.log("this.marginLeft:" + this.marginLeft);
       }, 300);
    }
    if (this.tagData.data.transactionInfo.isFixed === 'true' && this.tagData.data.transactionInfo.data.length > 1) {
      this.tagData.data.transactionInfo.data = this.tagData.data.transactionInfo.data.slice(0, 1);
    }
    this.initForm();
    const that = this;
    if (this.eventService.eventEmit.listenerCount('submit') > 0) {
      this.eventService.eventEmit.removeListener('submit');
    }
    this.eventService.eventEmit.on('submit' , item => {
      console.log('get submit comand');
      that.submit(item);
    });
  }
  initForm() {
    for (let i = 0; i < this.tagData.data.transactionInfo.data.length; i++) {
      const formItem = this.tagData.data.transactionInfo.data[i];
      const that = this;
      if (formItem.formKey && formItem.formKey.length > 1 && !this.formGroup.controls[formItem.formKey]) {
      this.formGroup.addControl(formItem.formKey, new FormControl(formItem.value, that.validators(formItem)));
    }
      if (formItem.rules && formItem.rules.length > 0) {
      const message: any = {};
      formItem.rules.forEach(rule => {
        // 将key 转小写
        message[rule.name.toLowerCase()] = rule.message;
      });
      message.label = formItem.label;
      this.allLabel[formItem.formKey] = message;
    }
  }
}
 // 数据校验
 validators(item) {
  const validators = [];
  if (item.rules && item.rules.length) {
    item.rules.forEach(rule => {
      if (rule.name === 'required' && rule.value === 'true') {
        validators.push(Validators.required);
      } else if (rule.name === 'minLength') {
        validators.push(Validators.minLength(Number(rule.value)));
      } else if (rule.name === 'maxLength') {
        validators.push(Validators.maxLength(Number(rule.value)));
      } else if (rule.name === 'min') {
        validators.push(Validators.min(Number(rule.value)));
      } else if (rule.name === 'max') {
        validators.push(Validators.max(Number(rule.value)));
      } else if (rule.name === 'pattern') {
        validators.push(Validators.pattern(rule.value));
      }
    });
  }
  return validators;
}
submit(item) {
  item.disabled = true;
  const formKeyObj: any = {};
  if (this.formGroup.valid) {
    // console.log(this.formGroup.value);
    const params = this.formGroup.value;
    // tslint:disable-next-line:forin
    for (const prop in params) {
      if (Array.isArray(params[prop])) {
        params[prop] = params[prop].join(',');
      }
      // 删除无效值
      if (prop === '') {
        // delete params[prop];
      }
      if (prop.indexOf('cus_') > -1) {
        const p = prop.substring(4, prop.length - 1);
        formKeyObj[p] = formKeyObj[p] ? formKeyObj[p] : [];
        formKeyObj[p].push(params[prop]);
        this.formGroup.removeControl(prop);
        delete params[prop];
      }
    }
    // 组合表单值
    for (const key in formKeyObj) {
      if (Array.isArray(formKeyObj[key])) {
        const value = formKeyObj[key].join(',');
        this.formGroup.patchValue({ [key]: value });
      }
    }

    Object.keys(params).forEach(key => {
      item.submit.content[key] = params[key];
    });
    if (this.tagData.data.transactionInfo.isFixed === 'true' && this.tagData.data.transactionInfo.data.length > 1) {
      item.submit.content[this.tagData.data.transactionInfo.data[1].formKey] = this.payMoney;
    }
    if (this.payMoney > this.siginMoney) {

      this.appGlobalService.showToast('佣金金额不能大于签约金额，请修改后再支付', 2500, 'middle');
      item.disabled = false;
      return;
    }
    item.submit.sessionId = localStorage.getItem('sessionId');
    this.httpService.post('application/submit', item.submit, res => {
        item.disabled = false;
        if (!res.success && res.message) {
          this.appGlobalService.showToast(res.message, 2000, 'middle');
        } else if (res.target) {
          const payParams = {
            pageId: res.target,
            params: res.params ? res.params : {},
            sessionId: localStorage.getItem('sessionId')
          };

          this.appGlobalService.goToForward(payParams);
        }
    }, err => {
      item.disabled = false;
    });

  } else {
    this.getErrors(this.formGroup);
    item.disabled = false;
  }
}

getErrors(form) {
  const errs = [];
  for (const name in form.controls) {
    // eg: controls[name] = phone
    if (form.controls[name].errors) {
      errs.push({ key: [name], err: form.controls[name].errors });
    }
  }
  if (errs.length) {
    const errItem = errs[0];

    const firstErrMsgKey = Object.keys(errItem.err)[0];
    console.log(errItem.key, '校验的字段名');
    const messageObj = this.allLabel[errItem.key];
    let showMessage = messageObj[firstErrMsgKey];
    if (errItem.err.rangeError !== undefined) {
      const label = messageObj.label.slice(-2);
      showMessage = `${messageObj.label}不得小于/等于最小${label}`;
    }
    this.appGlobalService.showToast(showMessage, 3000, 'top');

  }
}

changeValue(event, item, i) {

  if (event.detail.value.length > Number(item.maxLength)) {
    item.value = event.detail.value.slice(0, Number(item.maxLength));
    this.formGroup.patchValue({ [item.field]: item.value });
  }
  if (i === 0) {
    this.siginMoney = item.value;
  }
  if (i === 1) {
    this.payMoney = item.value;
    this.eventService.eventEmit.emit('payMoney' , "￥" + this.payMoney);
  }
  if (this.tagData.data.transactionInfo.isFixed === 'true' && i === 0) {
    this.payMoney = item.value * this.tagData.data.transactionInfo.fixedValue * 0.01;
    this.eventService.eventEmit.emit('payMoney' , "￥" + this.payMoney);
  }
  // this.checkNow(item);
}
  demoData() {
    this.tagData = {data:{
      type: "page",
      style: "page.AppSginConPageLogic",
      name: "AppSginConPageName",
      tagInfo: {
        marginBottom: "0.63rem",
        data: {
          tag: "客户",
          name: "张勇",
          property: "物业",
          company: "深圳来福士公司"
        }
      },


      transactionInfo: {
        marginBottom: "0.63rem",
        data: [{
          formType: "textInput",
          formKey: "rent",
          label: "签约金额(元)",
          placeHolder: "请输入金额",
          value: "",
          textType: 'number',
          rules: [
            {
              name: 'pattern',
              value: "[0-9]{1,7}",
              message: "请填写正确签约金额"
            },
            {
              name: 'required',
              value: true,
              message: "请填写正确签约金额"
            }
          ]
        },
        // {
        //   formType: "textInput",
        //   formKey: "pay",
        //   label: "佣金(元)",
        //   placeHolder: "请输入金额",
        //   value: "",
        //   textType: 'number',
        //   rules: [
        //     {
        //       name: 'pattern',
        //       value: "[0-9]{1,7}",
        //       message: "请填写正确佣金金额"
        //     },
        //     {
        //       name: 'required',
        //       value: true,
        //       message: "请填写正确佣金金额"
        //     }
        //   ]
        // }
        ],
        isFixed: "true",
        fixedValue: "5",
        labInfo: "按照合同约占比<font color='#FF6314'>5%</font>支付佣金"
      },
      card: {
        imageBackGroup: "Signing_bg_icon@3x.png",
        label: "我的累计签约额",
        infoData: {
          drawableLeft: "",
          name: "签约金额越高，加送推荐客户越多,服务更快精准"
        }
        ,
        process: {
          selectedBg: "#F234F",
          unselectedBg: "#FF853F",
          currentPrice: "1,000",
          startValue: "0",
          endValue: "60,000"
        }
        , bottomText: "*最终解释权归铺铺旺所有"
      },
      bottom:
      {
        name: "佣金(元)：",
        value: "￥0.00",
        label: "支付",
        btnDrawable: "../data.png",
        submit: {
          id: "38f6d396-f2a3-4fe5-8b07-7db3ebd7c15c",
          content: {
            name: "value"

          }
        }

      }

    }
    };
  }

}
